const router = require('koa-router')();
const GoodsScheme = require('../db/schema/home');
const GoodsListScheme = require('../db/schema/goods');

// 首页
router.get('/recommend', async (ctx, next) => {
  const res = await GoodsScheme.find()
  ctx.body = res[0]
  if (res) {
    ctx.body = {
      code: 200,
      data: res[0]
    }
  } else {
    ctx.body = {
      code: -1,
      data: []
    }
  }
})

// 分类列表页面tab对应数据
router.get('/classification', async (ctx, next) => {
  let { mallSubId } = ctx.query
  const res = await GoodsListScheme.find({ 'sub_id': mallSubId })
  if (res) {
    ctx.body = {
      code: 200,
      dataList: res
    }
  } else {
    ctx.body = {
      code: -1,
      dataList: []
    }
  }
})

// 获取单个商品详情
router.get('/one', async (ctx, next) => {
  const { id } = ctx.query
  const res = await GoodsListScheme.find({ id })
  if (res && res.length) {
    ctx.body = {
      code: 200,
      goodsOne: res[0]
    }
  } else {
    ctx.body = {
      code: -1,
      goodsOne: []
    }
  }
})

// 搜索
router.get('/search', async (ctx, next) => {
  const { keyword } = ctx.query;
  const reg = new RegExp(keyword,  'i');
  const res = await GoodsListScheme.find({
    name: {
      $regex: reg
    }
  });
  if (keyword && res && res.length) {
    ctx.body = {
      code: 200,
      goods: res
    }
  } else {
    ctx.body = {
      code: -1,
      goods: []
    }
  }
});

module.exports = router.routes();